#include "stdafx.h"
#include "ActionManager.h"

#include "RuleModel.h"
#include "Session.h"

CActionManager::CActionManager(void)
{
	m_ownSession = nullptr;
	m_pActionSet = nullptr;

	m_nextExecutionTime = 0xffffffff;
}

CActionManager::~CActionManager(void)
{
}

bool CActionManager::Create( CSession* session, int id )
{
	m_ownSession = session;

	m_pActionSet = CRuleModel::s_pInstance->GetSessionGroupRule( id );
	if( m_pActionSet == nullptr )
		return false;

	return true;
}

void CActionManager::Start()
{
	m_curActionSetIdx = 0;
    m_ActionExeCount = 0;
    m_ActionSetExeCount = 0;

    m_nextExecutionTime = 0;
}
	
void CActionManager::Update()
{
    //expired?
    if (m_nextExecutionTime == 0xffffffff)
        return;

    //check execution time!
	unsigned long currentTick = ::GetTickCount();
    if (m_nextExecutionTime != 0 && m_nextExecutionTime > currentTick)
        return;

    //get current action!
	Action* action = m_pActionSet->m_Actions[ m_curActionSetIdx ];

    //execute!!
	m_ownSession->ExecuteAction( m_ActionExeCount, action->m_actionName );
}

void CActionManager::AdvanceExecutionRule( Action* action )
{
	unsigned long currentTick = ::GetTickCount();

	//check current action interval time!
	if (action->m_interval > 0)
	{
		size_t variable = (action->m_interval/2);
		size_t random_variable = ::rand() % variable;
		m_nextExecutionTime = currentTick + action->m_interval + random_variable;
	}

	//advance current action execution count!
	++m_ActionExeCount;
	if (m_ActionExeCount < action->m_loop)
		return;
           
	//reset action execution count!
	m_ActionExeCount = 0;

	//advance action set index!
	++m_curActionSetIdx;
	if( m_curActionSetIdx < m_pActionSet->m_Actions.size() )
		return;
            
	//apply action set interval time!
	if (m_pActionSet->m_interval > 0)
		m_nextExecutionTime = currentTick + m_pActionSet->m_interval;

	//reset action set index!
	m_curActionSetIdx = 0;

	//advance action set execution count!
	++m_ActionSetExeCount;

	//check all action set has just finished!?
	if (m_ActionSetExeCount >= m_pActionSet->m_loop)
	{
		m_nextExecutionTime = 0xffffffff;
		Put( L"Job finished!! session[%d]", m_ownSession->GetSessioinID() );
		m_ownSession->JobFinished();
	}
}

void CActionManager::Pause()
{
	m_nextExecutionTime = 0xffffffff;
}

void CActionManager::Resume()
{
	Action* action = m_pActionSet->m_Actions[ m_curActionSetIdx ];
	AdvanceExecutionRule( action );
}